<template>
  <el-dialog
    title="轮播图编辑"
    v-model="visible"
    top="10vh"
    width="90%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-row :gutter="20">
      <el-col :span="16">
        <el-form
          ref="dataFormRef"
          :model="dataForm"
          :rules="dataFormRules"
          label-position="right"
          label-width="120px"
          v-loading="loading"
        >
          <el-form-item label="标题" prop="title">
            <el-input type="textarea" v-model="dataForm.title" placeholder="请输入标题"></el-input>
            <el-button @click="aiEvent('xuxie', 'title', '标题')">AI续写</el-button>
            <el-button @click="aiEvent('fanyi', 'title', '标题')">AI英语翻译</el-button>
          </el-form-item>
          <el-form-item label="跳转链接" prop="url">
            <el-input v-model="dataForm.url"></el-input>
          </el-form-item>
          <el-form-item label="pc端图片" prop="img">
            <div class="uploadBox">
              <el-upload
                accept="image/png, image/jpeg, image/jpg"
                action=""
                class="uploader-img"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="uploadClickEvent"
              >
                <el-image :src="imgUrl" v-if="imgUrl" class="infoImage"></el-image>
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
            <el-button type="primary" @click="clickOssEvent('img')">从素材库选择</el-button>
            <!-- <el-image style="width: 200px; height: 100px" :src="dataForm.img" @click="avatarClickEvent" /> -->
          </el-form-item>
          <el-form-item label="移动端图片" prop="wapImg">
            <div class="uploadBox">
              <el-upload
                accept="image/png, image/jpeg, image/jpg"
                action=""
                class="uploader-img"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="uploadCodeClickEvent"
              >
                <el-image :src="wapImgUrl" v-if="wapImgUrl" class="infoImage"></el-image>
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
            <el-button type="primary" @click="clickOssEvent('wapImg')">从素材库选择</el-button>
            <!-- <el-image style="width: 200px; height: 100px" :src="dataForm.wapImg" @click="avatarClickEvent" /> -->
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" v-model="dataForm.description" placeholder="请输入描述"></el-input>
            <el-button @click="aiEvent('xuxie', 'description', '描述')">AI续写</el-button>
            <el-button @click="aiEvent('fanyi', 'description', '描述')">AI英语翻译</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8">
        <div class="dialogue">
          <div class="title">大山AI对话框</div>
          <div class="dialogueBox">
            <div class="dialogueItems">
              <div class="dialogueItem" v-for="(item, index) in aiList" :key="index">
                <SvgIcon name="ai" />
                <div class="content">
                  {{ item.content }}
                </div>
              </div>
            </div>
            <div class="aiDialog">
              <div class="btnBox">
                <el-button round size="small" @click="clearDialog">清空对话框</el-button>
                <el-button round type="primary" size="small" v-for="item in aiBtnList" :key="item.keys" @click="insertionContent(item.keys)">赋予{{ item.label }}</el-button>
              </div>
              <el-alert title="赋予AI内容的时候是最新的一条，如需其它内容，请手动复制" type="warning" :closable="false" />
              <div class="content">
                <el-input type="textarea" v-model="aiContent" placeholder="请输入内容"></el-input>
                <div class="submintBtn">
                  <el-button type="primary" :loading="aiBtnLoading" round @click="submitAiDialog">
                    <el-icon><Position /></el-icon>
                    {{ !aiBtnLoading ? '发送' : 'AI生成中' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="updateOrCreate">确定</el-button>
    </template>

    <!-- 素材库 -->
    <OssWarehouse v-model="showOss" @change="enterOss"></OssWarehouse>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType } from 'vue'
import { UPDATE_MODEL_EVENT } from 'cm/contants'

import { createBanner, getBannerInfo, updateBanner, type ICreateOrUpdateBanner } from '@/api/banner'
import { fileUpload, type OssApiResult } from '@/api/oss'
import { ElMessage } from 'element-plus'
import { Plus, Position } from '@element-plus/icons-vue'

import OssWarehouse from '@/components/oss/index.vue'

import appConfig from '@/config/index'

import { aiSocket, aiDialogSocket } from '@/utils/socket'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  currId: {
    type: String,
    required: true,
    default: ''
  },
})

const emit = defineEmits([UPDATE_MODEL_EVENT, 'change'])

const visible = ref<boolean>(false)

const handleClose = () => {
  emit(UPDATE_MODEL_EVENT, false)
}

const defaultForm = {
  id: '',
  title: '',
  description: '',
  url: '',
  img: '',
  wapImg: '',
}
// 表单逻辑
const dataForm = ref<ICreateOrUpdateBanner>({ ...defaultForm })

const dataFormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  img: [{ required: true, message: '请上传pc端图片', trigger: 'blur' }],
  wapImg: [{ required: true, message: '请上传移动端图片', trigger: 'blur' }],
}
const loading = ref<boolean>(false)
// 查询Banner详情
const getBannerInfoApi = async (currId: string) => {
  loading.value = true
  const res = await getBannerInfo(currId)
  loading.value = false
  if (res?.code === 200) {
    dataForm.value = res.data as ICreateOrUpdateBanner;
    imgUrl.value = `${appConfig.api.staticUrl}${dataForm.value.img}`
    wapImgUrl.value = `${appConfig.api.staticUrl}${dataForm.value.wapImg}`
  }
}
  const imgType = ref<string>('img')
/** pc端图片上传 */
  const imgUrl = ref('');
  const imgUrlRaw = ref();
  const uploadClickEvent = async (file: any) => {
    if ('image/png, image/jpeg, image/jpg'.indexOf(file.raw.type) === -1) {
      ElMessage({ type: 'error', message: '文件类型错误' })
      return false
    }
    if (file.raw.size > 1024 * 1024 * 5) {
      ElMessage({ type: 'error', message: '上传图片大小不能超过 5M' })
      return false
    }
    console.log(file.raw)
    imgUrlRaw.value = file.raw;
    imgType.value = 'img';
    await confirmUpload('img')
    const reader = new FileReader()
    reader.readAsDataURL(file.raw)
    reader.onload = (e) => {
      imgUrl.value = `${appConfig.api.staticUrl}${dataForm.value.img}`
    }
  }

  /** 移动端图片上传 */
  const wapImgUrl = ref('');
  const wapImgUrlRaw = ref();
  const uploadCodeClickEvent = async (file: any) => {
    if ('image/png, image/jpeg, image/jpg'.indexOf(file.raw.type) === -1) {
      ElMessage({ type: 'error', message: '文件类型错误' })
      return false
    }
    if (file.raw.size > 1024 * 1024 * 5) {
      ElMessage({ type: 'error', message: '上传图片大小不能超过 5M' })
      return false
    }
    
    wapImgUrlRaw.value = file.raw
    await confirmUpload('wapImg')
    imgType.value = 'wapImg';
    const reader = new FileReader()
    reader.readAsDataURL(file.raw)
    reader.onload = (e) => {
      wapImgUrl.value = `${appConfig.api.staticUrl}${dataForm.value.wapImg}`
    }
  }

  // banner上传
  const confirmUpload = async (type: string) => {
    loading.value = true
    const formData = new FormData()
    const cropData = type === 'img' ? imgUrlRaw.value : wapImgUrlRaw.value;
    const businessText = type === 'logo' ? 'Banner-PC端图片' : 'Banner-移动端图片';

    formData.append('file', cropData)
    formData.append('business', businessText)
    const res = await fileUpload(formData)
    loading.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: '上传成功' });
      const data = res.data as OssApiResult[];

      if (type === 'img') {
        dataForm.value.img = data[0].url;
      }

      if (type === 'wapImg') {
        dataForm.value.wapImg = data[0].url;
      }

    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试' })
    }
  }

watch(
  () => props.modelValue,
  async () => {
    visible.value = props.modelValue
    if (props.modelValue && props.currId) {
      await getBannerInfoApi(props.currId)
    }
  }
)

const dataFormRef = ref()
const updateOrCreate = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      const res = await updateBanner(dataForm.value)
      loading.value = false
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '更新成功' })
        emit('change')
        handleClose()
      } else {
        ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
      }
    }
  })
}

// AI方法
const aiEvent = async (type: string, key: string, msg: string) => {
  loading.value = true
  let formKey = key;

  if (dataForm.value[formKey] === '') {
    ElMessage({ type: 'error', message: `请您输入${msg}` })
    loading.value = false
    return false;
  }

  const res = await aiSocket(type, dataForm.value[formKey]);

  if (res) {
    loading.value = false;
    const aiResultData = res as any
    dataForm.value[formKey] = `${aiResultData.data}`;
  }
}

// 素材库素材回填
const showOss = ref<boolean>(false)
const clickOssEvent = (type: string) => {
  imgType.value = type
  showOss.value = true
}

const enterOss = (checkList: any) => {
  if (imgType.value === 'img') {
    dataForm.value.img = checkList[0].name;
    imgUrl.value = checkList[0].url;
  }

  if (imgType.value === 'wapImg') {
    dataForm.value.wapImg = checkList[0].name;
    wapImgUrl.value = checkList[0].url;
  }
}

// AI对话框列表
const aiList = ref<Array<any>>([]);
const aiContent = ref<string>('');
const aiBtnLoading = ref<boolean>(false)
const aiBtnList = ref([
  {
    label: '标题',
    value: '',
    keys: 'title'
  },
  {
    label: '描述',
    value: '',
    keys: 'description'
  }
]);

// 清空AI对话框
const clearDialog = () => {
  aiList.value = []
}

// 插入AI对应值
const insertionContent = (keys: string) => {
  const value = aiBtnList.value.find(item => item.keys === keys)?.value;
  dataForm.value[keys] = value;
}

// 发送AI内容
const submitAiDialog = async () => {
  aiBtnLoading.value = true;
  const res = await aiDialogSocket(aiContent.value);
  if (res) {
    loading.value = false;
    const aiResultData = res as any
    aiList.value.push({
      content: `${aiResultData.data}`
    });
    aiBtnList.value.forEach(item => {
      item.value = `${aiResultData.data}`
    })
    aiBtnLoading.value = false;
  }
}
</script>

<style scoped>
  .infoImage {
    width: 200px;
    height: 100px;
  }
  .uploader-img :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .uploader-img :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 100px;
    text-align: center;
  }
</style>
